

from PyQt6.QtWidgets import QGraphicsView
from PyQt6.QtCore import pyqtSignal, QPoint, Qt, QRectF, QPointF
from PyQt6.QtCharts import QChartView


class QmyChartView(QChartView):
    
    mouseMove = pyqtSignal(QPoint) #鼠标移动
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setDragMode(QGraphicsView.DragMode.RubberBandDrag) #设置橡皮筋拖动模式
        self.__beginPoint = QPoint()
        self.__endPoint = QPoint()

    def mousePressEvent(self, event):
        """处理鼠标按下事件"""
        if event.button() == Qt.MouseButton.LeftButton:
            self.__beginPoint = event.pos()
        super().mousePressEvent(event)
    
    def mouseMoveEvent(self, event):
        """处理鼠标移动事件，发射当前位置信号"""
        self.mouseMove.emit(event.pos())
        super().mouseMoveEvent(event)
    
    def mouseReleaseEvent(self, event):
        """处理鼠标释放事件"""
        if event.button() == Qt.MouseButton.LeftButton:
            self.__endPoint = event.pos()
            if self.__beginPoint and self.__endPoint:
                rect = QRectF(QPointF(self.__beginPoint), QPointF(self.__endPoint))
                if rect.width() > 5 and rect.height() > 5:  # 防止误操作
                    self.chart().zoomIn(rect)
        elif event.button() == Qt.MouseButton.RightButton:
            self.chart().zoomReset()
        
        self.__beginPoint = None  # 重置起始点
        super().mouseReleaseEvent(event)

    def keyPressEvent(self, event):
        """处理键盘按键事件"""
        key = event.key()
        
        # 缩放控制
        if key == Qt.Key_Plus:        # + 放大
            self.chart().zoom(1.2)
        elif key == Qt.Key_Minus:     # - 缩小
            self.chart().zoom(0.8)
        elif key == Qt.Key_Home:      # Home 重置
            self.chart().zoomReset()
            
        # 方向键滚动
        elif key == Qt.Key_Left:      # ←
            self.chart().scroll(10, 0)
        elif key == Qt.Key_Right:     # →
            self.chart().scroll(-10, 0)
        elif key == Qt.Key_Up:        # ↑
            self.chart().scroll(0, -10)
        elif key == Qt.Key_Down:      # ↓
            self.chart().scroll(0, 10)
            
        # 翻页键滚动
        elif key == Qt.Key_PageUp:    # PageUp
            self.chart().scroll(0, -50)
        elif key == Qt.Key_PageDown:  # PageDown
            self.chart().scroll(0, 50)
            
        super().keyPressEvent(event)  # 调用父类处理